package javaagent.jdbc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Arrays;

/**
 * @author ：zzs
 * @version : 1.0
 * @date ：Created in 2022/3/12 19:19
 * @description：Connection代理实现类，采集需要的sql信息
 */
public class ConnectionHandler implements InvocationHandler {

    private final Connection connection;

    private final String[] connection_agent_methods = new String[]{"prepareStatement"};

    public ConnectionHandler(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        boolean statementMethod = Arrays.stream(connection_agent_methods).allMatch(n -> n.equals(method.getName()));
        Object result = new Object();
        SqlInfo sqlInfo = null;
        try {
            if (statementMethod) {
                // 采集信息
                sqlInfo = JdbcCollects.begin(connection, (String) args[0]);
            }
            result = method.invoke(connection, args);
            if (statementMethod && result instanceof PreparedStatement) {
                PreparedStatement preparedStatement = (PreparedStatement) result;
                // 注册PreparedStatement代理采集结束时间的信息
                result = JdbcCollects.proxyPreparedStatement(preparedStatement, sqlInfo);
            }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }
}
